package com.project.class4_11.homework;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.LocalTime;
import java.util.Locale;

public class ManProxy implements InvocationHandler {
    private Object targetObj;
    public ManProxy(Object targetObj){
        this.targetObj = targetObj;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(
                targetObj.getClass().getClassLoader(),
                targetObj.getClass().getInterfaces(),
                this
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            //执行目标方法
            Object returnObj = method.invoke(targetObj, args);
            return returnObj;
        }catch (Exception e){
            //XXX类在HH:mm:ss，执行XX方法时，抛出XX异常
            //类名
            String className = targetObj.getClass().getName();
            //得到日分秒
            LocalTime time = LocalTime.now();
            //得到目标方法名
            String methodName = method.getName();
            //得到异常对象的类名
            String exceptionName = e.getCause().getClass().getName();

            String info = className+"类在"+time+"，执行"+methodName+
                    "时，抛出"+exceptionName+"异常";
            System.out.println(info);

        }

        return null;
    }
}
